﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Main_Utilities_Users : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    string strsql = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {           
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!IsPostBack)
        {
            BindGroup();
            if (Request.QueryString["UserId"] != null)
            {
                BindUserDetails();
            }
            else
            {
                BindGridView();
            }
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["UserId"] != null)
        {
            UpdateUserDetails();
            Response.Redirect("Users.aspx");
        }
        else
        {
            InsertUserDetails();
            BindGridView();
        }
    }
    protected void InsertUserDetails()
    {
        try
        {
            strsql = "Select UserName from Login where UserName='" + TxtEmail.Text.Trim() + "'";
            DataTable DT = DU.getdata(strsql);
            if (DT.Rows.Count > 0)
            {
                hidHeading.Value = "Error:";
                hidMessage.Value = "Duplicate User Name!";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "ModalPopupsAlert(); ", true);
                return;
            }
            else
            {

                string GroupId = "";
                if (RBtnListActive.SelectedItem.Value == "1")
                {
                    GroupId = DdlGroup.SelectedValue.ToString();
                }
                else if (RBtnListActive.SelectedItem.Value == "0")
                {
                    GroupId = "0";
                }
                SqlParameter[] sparam =
                                    {
                                        new SqlParameter("@UserId","-1"),
                                        new SqlParameter("@UserName",TxtEmail.Text.Trim()),
                                        new SqlParameter("@Password",TxtPassword.Text.Trim()),
                                        new SqlParameter("@FirstName",TxtFirstName.Text.Trim()),
                                        new SqlParameter("@LastName",TxtLastName.Text.Trim()),
                                        new SqlParameter("@GroupId",GroupId.ToString()),
                                        new SqlParameter("@IsGroupActive",RBtnListActive.SelectedItem.Value),
                                        new SqlParameter("@Cname", Session["username"].ToString())
                                    };
                int result = DU.executeprocedure("USP_SaveUserLogin", sparam);
                if (result > 0)
                {

                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "ModalPopupsWait(); ", true);
                    //hidHeading.Value = "Success:";
                    //hidMessage.Value = "Updated Successfully";
                    //ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "ModalPopupsAlert(); ", true); 
                }
                else
                {
                    hidHeading.Value = "Error:";
                    hidMessage.Value = "Error When Creating User!";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "ModalPopupsAlert();", true);
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            hidHeading.Value = "Error:";
            hidMessage.Value = ex.Message.ToString();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "ModalPopupsAlert(); ", true);
            return;
        }
    }
    protected void UpdateUserDetails()
    {
        try
        {
            strsql = "Select UserName from Login where UserName='" + TxtEmail.Text.Trim() + "' and UserId<>'"+Request.QueryString["UserId"].ToString()+"'";
            DataTable DT = DU.getdata(strsql);
            if (DT.Rows.Count > 0)
            {
                hidHeading.Value = "Error:";
                hidMessage.Value = "Duplicate User Name!";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "ModalPopupsAlert(); ", true);
                return;
            }
            else
            {

                string GroupId = "";
                if (RBtnListActive.SelectedItem.Value == "1")
                {
                    GroupId = DdlGroup.SelectedValue.ToString();
                }
                else if (RBtnListActive.SelectedItem.Value == "0")
                {
                    GroupId = "0";
                }
                SqlParameter[] sparam =
                                    {
                                        new SqlParameter("@UserId",Request.QueryString["UserId"].ToString()),
                                        new SqlParameter("@UserName",TxtEmail.Text.Trim()),
                                        new SqlParameter("@Password",TxtPassword.Text.Trim()),
                                        new SqlParameter("@FirstName",TxtFirstName.Text.Trim()),
                                        new SqlParameter("@LastName",TxtLastName.Text.Trim()),
                                        new SqlParameter("@GroupId",GroupId.ToString()),
                                        new SqlParameter("@IsGroupActive",RBtnListActive.SelectedItem.Value),
                                        new SqlParameter("@Cname", Session["username"].ToString())
                                    };
                int result = DU.executeprocedure("USP_SaveUserLogin", sparam);
                if (result > 0)
                {

                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "ModalPopupsWait(); ", true);
                  
                }
                else
                {
                    hidHeading.Value = "Error:";
                    hidMessage.Value = "Error When Creating User!";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "ModalPopupsAlert();", true);
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            hidHeading.Value = "Error:";
            hidMessage.Value = ex.Message.ToString();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "ModalPopupsAlert(); ", true);
            return;
        }
    }
    protected void BindUserDetails()
    {
        SqlParameter[] sparam =
                                    {
                                        new SqlParameter("@UserId",Request.QueryString["UserId"].ToString())
                                    };

        DataTable DT = DU.getdatausingprocedure("USP_GetUserLogin", sparam);
        if (DT.Rows.Count > 0)
        {
            
            TxtEmail.Text = DT.Rows[0]["username"].ToString();
            ViewState["Password"] = DT.Rows[0]["password"].ToString();
           
            TxtFirstName.Text = DT.Rows[0]["firstname"].ToString();
            TxtLastName.Text = DT.Rows[0]["lastname"].ToString();
            string isGroupActive = "";
            if (DT.Rows[0]["isgroupactive"].ToString() == "True")
            {
                isGroupActive = "1";
            }
            else
            {
                isGroupActive = "0";
            }
            RBtnListActive.SelectedValue = isGroupActive;
            btnSubmit.Text = "Update";
            if (DT.Rows[0]["Groupid"].ToString() == "0")
            {
                DdlGroup.Enabled = false;
            }
            else
            {
                DdlGroup.Enabled = true;
            }

            TxtPassword.Attributes.Add("value", ViewState["Password"].ToString());
            //TxtPassword.Enabled = false;
        }
    }
    private void BindGroup()
    {
        DataTable DT = DU.getdatausingprocedure("usp_select_all_usergroup");
        DdlGroup.DataSource = DT;
        DdlGroup.DataTextField = "GroupName";
        DdlGroup.DataValueField = "GroupID";
        DdlGroup.DataBind();       
    }
    private void BindGridView()
    {
        SqlParameter[] sparam ={new SqlParameter("@UserId","-1")};
                                       
        DataTable DT = DU.getdatausingprocedure("USP_GetUserLogin",sparam);
        if (DT.Rows.Count > 0)
        {
            grdDisplay.DataSource = DT;
            grdDisplay.DataBind();
        }
        

    }
    protected void EnableDropdownList(object sender, EventArgs e)
    {
        if (RBtnListActive.SelectedItem.Value == "1")
        {
            DdlGroup.Enabled = true;
            BindGroup();
        }
        else if (RBtnListActive.SelectedItem.Value == "0")
        { 
            DdlGroup.Enabled = false;
        }
    }
    protected void grdDisplay_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdDisplay.PageIndex = e.NewPageIndex;
        BindGridView();
    }
    protected void grdDisplay_SelectedIndexChanged(object sender, EventArgs e)
    {
        string key = grdDisplay.SelectedDataKey.Value.ToString();
        Response.Redirect("Users.aspx?UserId="+key.ToString());
    }
}
